/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-02-17
*/
package com.rzico.account.controller.admin;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.account.entity.Payment;
import com.rzico.account.entity.Refunds;
import com.rzico.account.model.Attach;
import com.rzico.account.service.PaymentService;
import com.rzico.account.service.RefundsService;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Member;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.MemberService;
import com.rzico.core.entity.SysMch;
import com.rzico.core.entity.SysPlugin;
import com.rzico.core.entity.SysUser;
import com.rzico.core.plugin.PaymentPlugin;
import com.rzico.core.service.SysMchService;
import com.rzico.core.service.SysPluginService;
import com.rzico.core.service.SysSequenceService;
import com.rzico.core.service.SysUserService;
import com.rzico.entity.PageResult;
import com.rzico.entity.Pageable;
import com.rzico.exception.CustomException;
import com.rzico.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 退款单控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-02-17
 */
@Api(description = "退款单接口")
@RestController
@RequestMapping("/admin/refunds")
public class RefundsAdminController extends BaseController {

    @Autowired
    private RefundsService refundsService;

    @Autowired
    private SysPluginService sysPluginService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private SysSequenceService sysSequenceService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private SysMchService sysMchService;

    /**
     * 分页查询退款单
     *
     * @return
    */
    @ApiOperation("分页查询退款单")
    @GetMapping("/list")
    @ApiImplicitParams({@ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "orderSn", value = "订单号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "sn", value = "付款单号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "memberId", value = "客户Id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态", dataType = "Long", paramType = "query")
    })
    public CommResult<Refunds> list(Date startDate, Date endDate, String orderSn,String status, String sn,Long memberId, Pageable pageable) {
        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        if (startDate!=null){
            params.put("startDate",DateUtils.truncate(startDate, Calendar.DATE));
        }
        if (endDate!=null){
            params.put("endDate", DateUtils.addMilliseconds(DateUtils.addDays(endDate,1),-1));
        }

        if (status!=null){
            params.put("status",status);
        }

        if (memberId!=null){
            params.put("memberId",memberId);
        } else {
            Enterprise enterprise = enterpriseService.getCurrent();
            SysMch sysMch = sysMchService.selectByPrimaryKey(enterprise.getMchId());
            if (!sysMch.getMchType().equals(0))  {
                params.put("enterpriseId", enterprise.getId());
            }
        }

        if (StringUtils.isNotEmpty(orderSn)){
            params.put("orderSn", orderSn);
        }
        if (StringUtils.isNotEmpty(sn)){
            params.put("sn", sn);
        }

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<Refunds> list = refundsService.selectList(params);
        PageResult<Refunds> pageResult = new PageResult<Refunds>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);
    }

    /**
     * 查询单条退款单
     *
     * @return
    */
    @ApiOperation("查询单条退款单")
    @GetMapping("/find/{id}")
    public CommResult<Refunds> find(@PathVariable String id) {
        Refunds result = refundsService.findById(id);

        Map<String,Object> data = new HashMap<>();
        data.put("refunds",result);


        Map<String,Object> params = new HashMap<>();
        String sn = result.getSn();
        String [] sns = sn.split("-");
        params.put("groupSn",sns[0]);

        List<Refunds> refunds = refundsService.selectList(params);

        data.put("itemList",refunds);

        return CommResult.success(result);

    }

    /**
     * 保存退款单
     *
     * @param refunds
     * @return
     */
    @ApiOperation("保存退款单")
    @PostMapping("/save")
    public CommResult<Refunds> save(@RequestBody Refunds refunds) {
        int affectCount = refundsService.insert(refunds);
        if (affectCount <= 0) {
            return CommResult.error();
        }
        Refunds result = refundsService.findById(refunds.getId());
        return CommResult.success(result);

    }


    /**
     * 批量删除退款单
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除退款单", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除退款单,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<Refunds> del(@PathVariable String ids) {

        refundsService.deleteByIds(ids.split(","));
        return CommResult.success();
    }

    /**
     * 更新退款单
     *
     * @param refunds
     * @return
     */
    @Log(desc = "更新退款单", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("更新退款单")
    @PostMapping("/update")
    public CommResult<Refunds> update(@RequestBody Refunds refunds) {
        int affectCount = refundsService.updateByPrimaryKeySelective(refunds);
        if (affectCount <= 0){
            return CommResult.error();
        }
        Refunds result = refundsService.findById(refunds.getId());
        return CommResult.success(result);
    }

    /**
     * 对账
     *
     * @param id
     * @return
     */
    @Log(desc = "对账", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("对账")
    @PostMapping("/query")
    public CommResult<Refunds> query(Long id) {

        Refunds refunds = refundsService.findById(id);
        if (refunds.getPaymentPluginId()==null) {
            return CommResult.error("没有退款");
        }
//
//        if (!refunds.getStatus().equals(Refunds.STATUS_SUCCESS))  {
//            return CommResult.error("没有退款");
//        }

        PaymentPlugin paymentPlugin = sysPluginService.getPaymentPlugin(refunds.getPaymentPluginId());

        Enterprise enterprise = enterpriseService.findById(refunds.getEnterpriseId());

        SysMch sysMch = sysMchService.selectByPrimaryKey(enterprise.getMchId());
        if (sysMch.getMchType().equals(2) || sysMch.getMchType().equals(1)) {
            //特约商户,服务商代收
            enterprise = enterpriseService.findByMch(sysMch.getIsvId());
        }

        SysPlugin sysPlugin = sysPluginService.findByPlugin(enterprise.getMchId(),refunds.getPaymentPluginId());
        if (sysPlugin==null) {
            return CommResult.error("无效插件编号");
        }
        Map<String,Object> resultMap = paymentPlugin.refundQuery(sysPlugin,refunds.getSn(),refunds.getTranSn(),null);

        if ("0000".equals(resultMap.get("return_code").toString())) {
            try {
                refundsService.handle(refunds.getSn(),resultMap.get("tranSn").toString());
                return CommResult.success(refunds);
            } catch (Exception e) {
                return CommResult.error("退款通知失败");
            }
        } else {
            if (!"0001".equals(resultMap.get("return_code").toString()) && !"9999".equals(resultMap.get("return_code").toString())) {
                refunds.setStatus(Refunds.STATUS_FAILURE);
                refundsService.updateByPrimaryKeySelective(refunds);
            }
            return CommResult.error(resultMap.get("error_msg").toString());
        }

    }

    /**
     * 提交退款
     *
     * @param id
     * @return
     */
    @Log(desc = "提交退款", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("提交退款")
    @PostMapping("/submit")
    public CommResult<Payment> submit(Long id) {
        Refunds refunds = refundsService.findById(id);

        if (!refunds.getStatus().equals(Refunds.STATUS_WAITING))  {
            return CommResult.error("不能重复退款");
        }

        try {
            refundsService.submit(id);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return CommResult.error("提交退款失败");
        }
        refunds = refundsService.findById(id);
        if (refunds.getStatus().equals(Refunds.STATUS_SUCCESS) || refunds.getStatus().equals(Refunds.STATUS_REFUNDED)) {
            return CommResult.success("提交退款成功");
        } else {
            return CommResult.error(refunds.getTranSn());
        }

    }

}
